// pages/storedValue/storedValue.js
const rechargeService = require('../../../api/rechargeService.js')
const memberService = require('../../../api/memberService.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    storedValue: 0, // 储值余额
    rechargeList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMbrBalance();
    this.getRechargeList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 查询当前用户的储值余额
   */
  getMbrBalance: function () {
    memberService.getMbrBalance().then(res => {
      this.setData({
        storedValue: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 获取充值金额列表
   */
  getRechargeList: function () {
    rechargeService.query().then(res => {
      // console.log(res)
      let tempArr = [];
      res.forEach(item => {
        tempArr.push({
          ...item,
          active: false
        })
      })
      this.setData({
        rechargeList: tempArr
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 点击每一个价格，选中，改变类名
   */
  clickCheckPrice: function(e) {
    let tempList = this.data.rechargeList;
    tempList.forEach(item => {
      if (e.currentTarget.dataset.id === item.rechangeMoneyId){
        item.active = !item.active;
      } else {
        item.active = false;
      }
    })
    this.setData({
      rechargeList: tempList
    })
  },
  /**
   * 充值按钮点击事件
   * 获取当前被选中的价格选项
   */
  handleRecharge: function() {
    let rechangeMoneyId = '';
    this.data.rechargeList.forEach(item => {
      if(item.active) {
        rechangeMoneyId = item.rechangeMoneyId
      }
    })
    if (rechangeMoneyId) {
      // 创建充值订单
      rechargeService.createOrder(rechangeMoneyId).then(res => {
        // 根据当前的订单id获取支付签名
        let orderId = res.id;
        let payMethod = 'WX_MINI_APP'; // WX_MINI_APP小程序 SWIFTPASS威富通
        rechargeService.getPaySign(orderId, payMethod).then(res => {
          console.log(res)
          // 解析拿到的签名等字段数据
          let resData = JSON.parse(res);
          console.log(resData)
          let sign = JSON.parse(resData.sign);
          console.log(sign)          
          let packageValue = ''
          if (payMethod === 'SWIFTPASS') {
            packageValue = sign.package
          } else if (payMethod === 'WX_MINI_APP') {
            packageValue = sign.packageValue
          }
          // 调起微信支付
          wx.requestPayment({
            'timeStamp': sign.timeStamp,
            'nonceStr': sign.nonceStr,
            'package': packageValue,
            'signType': sign.signType,
            'paySign': sign.paySign,
            'success': function (res) {
              wx.showToast({
                title: '充值成功',
                icon: 'none',
                duration: 2000
              })
            },
            'fail': function (res) {
              console.log('支付失败----------')
              console.log(res)
              if (res.errMsg === 'requestPayment:fail cancel') {
                wx.showToast({
                  title: '您取消了支付~',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      wx.showToast({
        title: "请选择要充值的金额",
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 跳转修改密码
   */
  toChangeBalancePass: function() {
    wx.navigateTo({
      url: '../changeBalancePass/changeBalancePass',
    })
  },
  /**
   * 跳转到储值明细
   */
  toBalancePayList: function() {
    wx.navigateTo({
      url: '../balancePayList/balancePayList',
    })
  }
})